package com.ruoyi.web.controller.airplane;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.system.domain.info.AppVersionInfo;
import com.ruoyi.system.domain.info.DataPackageInfo;
import com.ruoyi.system.domain.info.PackageInfo;
import com.ruoyi.system.domain.vo.AppVersionUploadResult;
import com.ruoyi.system.service.IAppPackageService;
import com.ruoyi.system.utils.BsDiffUtil;
import com.ruoyi.system.utils.FileUploadUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Api(tags = "应用包上传管理")
@RestController
@RequestMapping("/system/package")
@RequiredArgsConstructor
@Slf4j
public class AppPackageController  extends BaseController {


    private final IAppPackageService packageService;


    @Value("${spring.servlet.multipart.max-file-size}")
    private String maxFileSizeConfig;


    @Value("${file.storage.package}")
    private String storagePath;

    @ApiOperation("上传HarmonyOS应用包")
    @PostMapping("/upload/appCatalog")
    public R<PackageInfo> uploadHarmonyPackage(@RequestPart MultipartFile file) {
        if (!file.getOriginalFilename().toLowerCase().endsWith(".hap")) {
            return R.fail("仅支持.hap格式文件");
        }
        try {
            // 1. 获取文件大小（字节）
            long fileSizeBytes = file.getSize();
            // 2. 转换为 MB（保留2位小数）
            double fileSizeMB = fileSizeBytes / (1024.0 * 1024.0);
            //字节后端入库
            String formattedSize = String.format("%.2f MB", fileSizeMB);

            // 2. 获取配置限制并转换为MB（用于业务校验）
            long maxFileSizeBytes = parseSizeToBytes(maxFileSizeConfig);
            double maxFileSizeMB = maxFileSizeBytes / (1024.0 * 1024.0);
            if (fileSizeMB > maxFileSizeMB) {
                return R.fail("文件大小超出限制: " + maxFileSizeConfig);
            }

            // 计算文件哈希
            String fileHash = DigestUtils.md5DigestAsHex(file.getInputStream());
            // 调用服务层处理
            return R.ok(packageService.processPackageUpload(file.getInputStream(), file.getOriginalFilename(), fileHash, fileSizeMB, formattedSize));
        } catch (IOException e) {
            throw new ServiceException("应用包上传失败: " + e.getMessage());
        }

    }


    @ApiOperation("上传HarmonyOS对应版本应用包")
    @PostMapping("/upload/appVersion")
    public R<AppVersionUploadResult> uploadHarmonyVersionPackage(@RequestPart MultipartFile file) {

        if (!file.getOriginalFilename().toLowerCase().endsWith(".hap")) {
            return R.fail("仅支持.hap格式文件");
        }
        try {
            // 1. 获取文件大小（字节）
            long fileSizeBytes = file.getSize();
            // 2. 转换为 MB（保留2位小数）
            double fileSizeMB = fileSizeBytes / (1024.0 * 1024.0);
            //字节后端入库
            String formattedSize = String.format("%.2f MB", fileSizeMB);
            long maxFileSizeBytes = parseSizeToBytes(maxFileSizeConfig);
            double maxFileSizeMB = maxFileSizeBytes / (1024.0 * 1024.0);
            if (fileSizeMB > maxFileSizeMB) {
                return R.fail("文件大小超出限制: " + maxFileSizeConfig);
            }
            // 计算文件哈希
            String fileHash = DigestUtils.md5DigestAsHex(file.getInputStream());
            log.info("文件哈希: " + fileHash);
            // 调用服务层处理
            return R.ok(packageService.processPackageVersionUpload(file.getInputStream()
                    , file.getOriginalFilename(), fileHash, fileSizeMB, formattedSize));
        } catch (IOException e) {
            throw new ServiceException("应用包上传失败: " + e.getMessage());
        }

    }

    @ApiOperation("上传对应版本数据包")
    @PostMapping("/upload/dataPackage")
    public R<DataPackageInfo> uploadHarmonyDataPackage(@RequestPart MultipartFile file) {

        try {
            // 1. 获取文件大小（字节）
            long fileSizeBytes = file.getSize();
            // 2. 转换为 MB（保留2位小数）
            double fileSizeMB = fileSizeBytes / (1024.0 * 1024.0);
            double result = Math.round(fileSizeMB * 100.0) / 100.0;
            //字节后端入库
            String formattedSize = String.format("%.2f MB", result);
            long maxFileSizeBytes = parseSizeToBytes(maxFileSizeConfig);
            double maxFileSizeMB = maxFileSizeBytes / (1024.0 * 1024.0);
            if (result > maxFileSizeMB) {
                return R.fail("文件大小超出限制: " + maxFileSizeConfig);
            }

            // 计算文件哈希
            String fileHash = DigestUtils.md5DigestAsHex(file.getInputStream());
            // 调用服务层处理
            return R.ok(packageService.processPackageDataUpload(file.getInputStream(), file.getOriginalFilename(), fileHash, result, formattedSize));
        } catch (IOException e) {
            throw new ServiceException("应用包上传失败: " + e.getMessage());
        }

    }


    @GetMapping("/check-config")
    public String checkConfig() {
        return "当前文件大小限制: " + maxFileSizeConfig; // 访问此端点确认配置值
    }


    /**
     * 将配置的尺寸字符串（如"10GB"）转换为字节数
     */
    private long parseSizeToBytes(String sizeStr) {
        sizeStr = sizeStr.trim().toUpperCase();
        try {
            if (sizeStr.endsWith("KB")) {
                return Long.parseLong(sizeStr.substring(0, sizeStr.length() - 2)) * 1024;
            } else if (sizeStr.endsWith("MB")) {
                return Long.parseLong(sizeStr.substring(0, sizeStr.length() - 2)) * 1024 * 1024;
            } else if (sizeStr.endsWith("GB")) {
                return Long.parseLong(sizeStr.substring(0, sizeStr.length() - 2)) * 1024 * 1024 * 1024;
            } else if (sizeStr.endsWith("TB")) {
                return Long.parseLong(sizeStr.substring(0, sizeStr.length() - 2)) * 1024 * 1024 * 1024 * 1024;
            }
            return Long.parseLong(sizeStr); // 无单位默认字节
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("无效的文件大小配置: " + sizeStr);
        }
    }


    @PostMapping("/generate")
    @ApiOperation("模拟生成补丁,测试工具类是否可用")
    public String generatePatch(
            @RequestParam("oldFile") MultipartFile oldFile,
            @RequestParam("newFile") MultipartFile newFile,
            @RequestParam(value = "timeout", defaultValue = "300") long timeout) {

        try {
            // 保存上传文件
            File old = FileUploadUtil.saveUploadedFile(oldFile, "old_");
            File newer = FileUploadUtil.saveUploadedFile(newFile, "new_");
            File patch = new File(storagePath + "patch_" + System.currentTimeMillis() + ".diff");

            // 生成差分包
            boolean success = BsDiffUtil.generatePatch(old, newer, patch, timeout);
            return success ? "Patch generated: " + patch.getAbsolutePath()
                    : "Patch generation failed";
        } catch (Exception e) {
            return "Error: " + e.getMessage();
        }
    }

}